<?php
namespace app\api\controller;

use app\api\common\controller\Api;
use think\facade\Db;
// use app\api\common\controller\MidOrder;
use app\api\model\Order as modelOrder;
use app\api\common\controller\PriceSystem;
use Endroid\QrCode\QrCode;

/**
 * @Apidoc\Title("Demo.php")
 * @Apidoc\Group("api")
 */
class Order extends Api
{
	public function _structure(){
// $this->user_member_id=13756;
        if($this->user_member_id == 0){
        	$this->result('请先登录',[],400);
        }
   
    }

	//订单确认
	public function placeOrder(){
        $data = $this->request::param();

            $rule = [
             'users|游客信息' => 'require',
                // 'name|姓名' => 'require',
                // 'mobile|联系电话'  => 'require|number|mobile',

            ];
            $msg=$this->validate($data, $rule);
            if($msg!==true) $this->result($msg, [],400,'json');
        if(empty($data['users'])) $this->result('请选择至少1位游客',[],400,'json');
        $data['number']=$data['number']?$data['number']:1;
        if($data['server_type']==1){//购票
            $beginToday=mktime(0,0,0,date('m'),date('d'),date('Y'));
            $endToday=mktime(0,0,0,date('m'),date('d')+1,date('Y'))-1;
            $use_time=strtotime(date('Y-').$data['use_time']);
       
            // if($use_time>=$beginToday && $use_time<=$endToday){
              
            //     if(time()>$beginToday+18*3600){
            //         $this->result('今日票停售请选择其它时间',[],400);
            //     }
            // }
     
            $ticket_price=Db::name('ticket_price')->where('tree_ticket_id',$data['server_id'])->field('activity_price,price')->find();
            $price=$ticket_price['price'];
            $activity_price=$ticket_price['activity_price'];
            $server_id=$data['server_id'];
        }elseif($data['server_type']==2){//租赁
           $lease=Db::name('lease')->where('id',$data['server_id'])->find();
           $server_id=$data['server_id'];
            $order_server['amount']=$lease['deposit'];
            $order['amount'] =$lease['deposit'];
           if($lease['spec_type']=="more"){
                $order_server['house_num']=$data['house_id'];
                $order_server['house_title']=Db::name('house')->where('id',$data['house_id'])->value('title');
                $spec_id=$data['spec_id'];
                $spec_id=explode(',',$data['spec_id']);
                sort($spec_id);
                if(count($spec_id)==1){
                        $time_id=$spec_id[0];
                        $where_price=[
                            ['lease_id','=',$data['server_id']],
                            ['day_time','=',date('w',time())],
                            ['sku_val','like','%'.$time_id.'%']
                        ];
                         $use_time=time();
                }else{
                    $time_id=Db::name('spec_item')->where('spec_id',1)->where('item',date('w',$spec_id[1]))->value('id');
                    $where_price=[
                        ['lease_id','=',$data['server_id']],
                        ['day_time','=',date('w',$spec_id[1])],
                        ['sku_val','like','%'.$spec_id[0].'%']
                    ];
                     $use_time=$spec_id[1];
                }
               
                $lease_price=Db::name('lease_price')->where($where_price)->find();
                $order_server['time_id']=$time_id;
                $price=$lease_price['price'];
                $activity_price=$lease_price['activity_price'];
           }else{

              $price=$lease['price'];
              $activity_price=$lease['activity_price'];
              $use_time=strtotime($data['use_time']);
           }
        }

		$out_trade_no = orderNumber();
        $order['out_trade_no'] = $out_trade_no;
        $order['members_id'] = $this->user_member_id;
        $order['orders_status'] = 0;
        $order['use_time'] =$use_time?$use_time:time();
        $order['create_time'] =time();
        $order['price'] =$activity_price*$data['number'];
        // $order['tel'] =$data['mobile'];
        // $order['name'] =$data['name'];
        $order['users']=$data['users'];
        Db::startTrans();
        try{
        	$order_id=Db::name('order') -> insertGetId($order);
            $order_server['number']=$data['number'];
            $order_server['server_id']=$server_id;
            $order_server['type']=$data['server_type'];
            $order_server['price']=$price;
            $order_server['act_price']=$activity_price;
            $order_server['order_id']=$order_id;
        	Db::name('order_server')->insert($order_server);
        	Db::commit();
        
        	$this->result('下单成功',['out_trade_no'=>$out_trade_no,'order_id'=>$order_id],200);
        }catch(Exception $e){
        	Db::rollback();
        	$this->result('下单失败',[],400);

        }
	}

	   // 团票预约信息
     public function makeAppointment(){
            $post = request()->param();
            $rule = [
                  'users|游客信息' => 'require',
                // 'name|姓名' => 'require',
                // 'tel|联系电话'  => 'require|number|mobile',
                'desc|描述'=>'require',
                'point_date|预订日期'=>'require',
                'number|人数'=>'require',

            ];
            $msg=$this->validate($post, $rule);
            if($msg!==true) $this->result($msg, [],400,'json');
        try{
            $out_trade_no = orderNumber();
            $post['out_trade_no'] ="YD". $out_trade_no;
        	$post['members_id']=$this->user_member_id;
            $post['point_date']=strtotime($post['point_date']);
            $post['create_time']=time();
           $res=Db::name('appointment')->insertGetId($post);
        }catch(Exception $e){
            $this->result($e->getMessage(), [],400,'json');
        }
         $this->result('预约成功',$res,200,'json');   
     }
     public function getMyOrderList(){
         $state=input('status');
         $page=input('page')?input('page'):1;
         $size=input('size')?input('size'):20;
         $where=[
            ['members_id','=',$this->user_member_id]
         ];
           
         if(strlen($state)>0)  array_push($where,['orders_status','=',$state]);
         $orderData=Db::name('order')->field('id,out_trade_no,orders_status')->where($where)->order('create_time desc')->page($page,$size)->select()->toArray();
         foreach ($orderData as $k => $v) {
            $order_server=Db::name('order_server')->where('order_id',$v['id'])->select()->toArray();
            foreach ($order_server as $kk => $vv) {
                if($vv['type']==1){
                        $ticket=Db::name('ticket')->where('id',$vv['server_id'])->field('title,thumb')->find();
                        $order_server[$kk]['title']=$ticket['title'];
                        $order_server[$kk]['image']=$ticket['thumb'];
                }elseif($vv['type']==2){
                    $lease=Db::name('lease')->where('id',$vv['server_id'])->find();
                     $order_server[$kk]['title']=$lease['title'];
                     $order_server[$kk]['image']=$lease['thumb'];
                     if($vv['time_id']) $order_server[$kk]['time_interval']=Db::name('spec_item')->where('id',$vv['time_id'])->value('item');
                }
                 $order_server[$kk]['price']=$vv['price']*$vv['number'];
                $order_server[$kk]['act_price']=$vv['act_price']*$vv['number'];
            }
            $orderData[$k]['childern']=$order_server;
         }
         $this->result('success',$orderData,200,'json');  
     }
     public function getOrderDetail(){
        $order_id=input('order_id');
        $where=[
            ['members_id','=',$this->user_member_id],
            ['id','=',$order_id]
        ];
        $orderData=Db::name('order')->field('id,out_trade_no,tel,name,use_time,create_time,code,orders_status,users,amount')->where($where)->find();
        $refund=Db::name('refund')->where('orders_id',$order_id)->value('amount');
        $orderData['refund_amount']=$refund?$refund:0;
        $orderData['users']=Db::name('user')->whereIn('id',$orderData['users'])->select();
        if($orderData['code']){
            $qrCode = new QrCode($orderData['code']);
           header('Content-Type: '.$qrCode->getContentType());
          // / / echo $qrCode->writeString();die;
          $img=$qrCode->writeDataUri();
          $orderData['code_url']=$img;
        }else{
            $orderData['code_url']='';
        }

        $order_server=Db::name('order_server')->where('order_id',$orderData['id'])->select()->toArray();
        foreach ($order_server as $kk => $vv) {
               if($vv['type']==1){
                        $ticket=Db::name('ticket')->where('id',$vv['server_id'])->field('title,thumb')->find();
                        $order_server[$kk]['title']=$ticket['title'];
                        $order_server[$kk]['image']=$ticket['thumb'];
                }elseif($vv['type']==2){
                    $lease=Db::name('lease')->where('id',$vv['server_id'])->find();
                     $order_server[$kk]['title']=$lease['title'];
                     $order_server[$kk]['image']=$lease['thumb'];
                     if($vv['time_id']) $order_server[$kk]['time_interval']=Db::name('spec_item')->where('id',$vv['time_id'])->value('item');
                }
                $order_server[$kk]['price']=$vv['price'];
                $order_server[$kk]['act_price']=$vv['act_price'];
        }
        $orderData['childern']=$order_server;
        $orderData['create_time']=date('Y-m-d H:i:s',$orderData['create_time']);
        $orderData['use_time']=date('Y-m-d',$orderData['use_time']);
        $this->result('success',$orderData,200,'json'); 
     }
     //我的预定
     public function getMyAppointment(){
        $data=Db::name('appointment')->where('members_id',$this->user_member_id)->select();
        $this->result('success',$data,200,'json'); 
     }
     //预定详情
     public function getAppointDetail(){
        $appointment_id=input('appointment_id');
        $data=Db::name('appointment')->where('id',$appointment_id)->find();
        $data['users']=Db::name('user')->whereIn('id',$data['users'])->select();
        $ticket=Db::name('ticket')->where('id',$data['ticket_id'])->field('title,thumb')->find();
        $data['title']=$ticket['title'];
        $data['image']=$ticket['thumb'];
        $data['create_time']=date('Y-m-d H:i:s' );
        $data['point_date']=date('Y-m-d' );
        $this->result('success',$data,200,'json'); 
     }
     //支付
     public function pay(){
    	if($this->user_member_id == 0){
            $this->result('请先登录',[],400);
        }
		$out_trade_no = $this->request::param('out_trade_no');
		
		$info = Db::name('order') -> where('out_trade_no',$out_trade_no) -> field('id,price,orders_status,amount') -> findOrEmpty();
	
		if(count($info) == 0){
			$this->result('该订单不存在',[],400);
		}
		if($info['orders_status'] == 0){
			if($info['price'] > 0){
				$amount = $info['price'] + $info['amount'];
				$order_id = $info['id'];
				$data = $this->prepareOnlinePay($order_id,$amount);
				$this->result('ok',$data,200);
			
			}else{//零元订单处理
				Db::name('order') -> where('id',$info['id']) -> update(['orders_status' => 1,'code' => $this->getcode()]);
				$this->result('付款失败',[],400);
			}
		}else{
			$this->result('该订单不是未支付状态',[],400);
		}
		
		
	}
	//退款
	public function refund(){
	    if($this->user_member_id == 0){
            $this->result('请先登录',[],400);
        }
		$out_trade_no = $this->request::param('out_trade_no');
		$info = Db::name('order') -> where('out_trade_no',$out_trade_no) -> field('id,price,orders_status,amount') -> findOrEmpty();
	
		if(count($info) == 0){
			$this->result('该订单不存在',[],400);
		}
		if($info['orders_status'] == 1){
		    $h = date('H');
		    $paid_at = Db::name('wechat_payment') -> where('orders_id',$info['id']) -> value('paid_at');
		    //if ($h <= 18 && $h > 0 && date('Y-m-d',strtotime($paid_at)) == date('Y-m-d',time())){
		       
                $refundMoney = $info['price'] + $info['amount'];
                $flow_id = Db::name('wechat_payment') -> where('orders_id',$info['id']) -> value('flow_id');
                $refundNo = createSerialNumber();
                $result = $this->payApp->refund->byOutTradeNumber($flow_id, $refundNo, $refundMoney*100, $refundMoney*100, [
                    // 可在此处传入其他参数，详细参数见微信支付文档
                    //'refund_desc' => '订单退款',
                    'notify_url' => 'https://tree.chemeijia.com/api/wx/refund'
                
                ]);
                //Db::name('order') -> where('id',$info['id']) -> update(['orders_status' => 3,'refund_time' => time()]);
		        $this->result('退款提交成功，1-2工作日原路退回',[],200);
		    //}else{
		        //$this->result('支付订单下午18:00之后不支持退款',[],400);
		    //}
		    
		}else{
		    $this->result('该订单不满足退款要求',[],400);
		}
	}
	//退款详情
	public function refundDetail(){
	    if($this->user_member_id == 0){
            $this->result('请先登录',[],400);
        }
		$out_trade_no = $this->request::param('out_trade_no');
		$info = Db::name('order') -> where('out_trade_no',$out_trade_no) -> field('id,price,orders_status,refund_time') -> findOrEmpty();
		$info['price'] = Db::name('refund') -> where('orders_id',$info['id']) -> sum('amount');
		$info['refund_time'] = date('Y-m-d H:i:s',$info['refund_time']);
		$info['status'] = 1;//1-审核 2-完成
		$this->result('OK',$info,200);
	}
}
